﻿//-----------------------------------------------------------------------
// <copyright file="KeepNecessaryDataStage.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>20/03/2013</date>

using ConsoleHoster.Common.Utilities;
using ConsoleHoster.Common.Utilities.IO;
using System;
using System.IO;

namespace AppUpdateInstaller.Model.InstallationStages
{
	internal sealed class KeepNecessaryDataStage : InstallationStageBase
	{
		private readonly string archiveFilePath;
		private readonly string updateFolder;
		private readonly string binariesFolder;
		private readonly string[] filesToKeep;

		public KeepNecessaryDataStage(string argArchiveLocation, string argBinariesFolderPath, IProcessManager argProcessManager, IFileSystemContentProvider argFileSystemContentProvider, Action argShutdownLogic, string[] argFilesToKeep)
			: base(argProcessManager, argFileSystemContentProvider, argShutdownLogic)
		{
			if (!this.FileSystemContentProvider.FileExists(argArchiveLocation))
			{
				throw new FileNotFoundException("The specified archive file is not found");
			}

			if (!this.FileSystemContentProvider.DirectoryExists(argBinariesFolderPath))
			{
				throw new DirectoryNotFoundException("Invalid binaries folder specified");
			}

			if (argFilesToKeep == null)
			{
				throw new ArgumentNullException("argFilesToKeep");
			}

			this.archiveFilePath = argArchiveLocation;
			this.updateFolder = Path.Combine(new FileInfo(this.archiveFilePath).Directory.FullName, Guid.NewGuid().ToString());
			this.binariesFolder = argBinariesFolderPath;
			this.filesToKeep = argFilesToKeep;
		}

		public override void Run()
		{
			this.NotifyProgressChange(new InstallationStageProgressEventArgs { Status = "Extracting update package..." });
			foreach (string tmpFile in this.filesToKeep)
			{
				this.FileSystemContentProvider.CopyFile(tmpFile, Path.Combine(this.updateFolder, new FileInfo(tmpFile).Name), true);
			}
		}
	}
}
